import os
from datetime import datetime

from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import (QApplication, QVBoxLayout, QLabel, QFileDialog, QMessageBox, QScrollArea, QToolButton,
                             QDialog, QMenu)


class ImageViewer(QDialog):
    def __init__(self, image_path, parent=None):
        super().__init__(parent)
        self.setWindowTitle("图片预览")
        self.setWindowFlags(self.windowFlags() | Qt.WindowMaximizeButtonHint)

        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)

        scroll = QScrollArea()
        scroll.setWidget(self.image_label)
        scroll.setWidgetResizable(True)

        layout = QVBoxLayout()
        layout.addWidget(scroll)
        self.setLayout(layout)

        self.load_image(image_path)

    def load_image(self, image_path):
        if not image_path or not os.path.exists(image_path):
            self.image_label.setText("图片不存在")
            return

        pixmap = QPixmap(image_path)
        if pixmap.isNull():
            self.image_label.setText("无法加载图片")
            return

        self.image_label.setPixmap(pixmap)
        self.resize(700, 700)


class ImageButton(QToolButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setIconSize(QSize(100, 100))
        self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.clicked.connect(self.on_click)
        self.image_path = ""
        # 初始化固定图标和文本
        self.setIcon(QIcon.fromTheme("image-missing"))
        self.setText("添加图片")

        # 添加右键菜单
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)

    def set_image(self, image_path):
        self.image_path = image_path
        if image_path and os.path.exists(image_path):
            # 仅显示文件名
            file_name = os.path.basename(image_path)
            self.setText(file_name)
        else:
            self.setText("添加图片")
    def show_context_menu(self, pos):
        """右键删除功能"""
        if not self.image_path:
            return
        menu = QMenu(self)
        delete_action = menu.addAction("删除图片")
        delete_action.triggered.connect(lambda: self.set_image(""))
        menu.exec_(self.mapToGlobal(pos))
    def on_click(self):
        # 检查剪贴板是否有图片
        clipboard = QApplication.clipboard()
        mime_data = clipboard.mimeData()

        if mime_data.hasImage():
            reply = QMessageBox.question(
                self, "粘贴图片",
                "剪贴板中有图片，是否使用?",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes
            )

            if reply == QMessageBox.Yes:
                self.paste_image_from_clipboard()
                return

        # 如果没有图片或用户选择不使用，则正常选择文件
        if self.image_path and os.path.exists(self.image_path):
            viewer = ImageViewer(self.image_path, self.parent())
            viewer.exec_()
        else:
            file, _ = QFileDialog.getOpenFileName(
                self, "选择图片", "",
                "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)"
            )
            if file:
                self.set_image(file)

    def paste_image_from_clipboard(self):
        """从剪贴板粘贴图片"""
        clipboard = QApplication.clipboard()
        image = clipboard.image()

        if image.isNull():
            QMessageBox.warning(self, "错误", "剪贴板中没有有效的图片!")
            return

        # 创建临时目录
        temp_dir = os.path.join("temp", "clipboard_images")
        os.makedirs(temp_dir, exist_ok=True)

        # 生成唯一文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        temp_path = os.path.join(temp_dir, f"pasted_{timestamp}.png")

        # 保存图片
        if not image.save(temp_path, "PNG"):
            QMessageBox.warning(self, "错误", "保存剪贴板图片失败!")
            return

        self.set_image(temp_path)
